package com.whfc.ms.interceptor;

import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.common.util.JSONUtil;
import com.whfc.common.util.RequestAttr;
import com.whfc.common.util.SessionAttr;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.service.SysDeptService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author qzexing
 * @version 1.0
 * @date 2021-06-22 16:11
 */
@Component
public class RequestHeaderInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0")
    private SysDeptService sysDeptService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("登录请求头认证过滤器");
        //验证组织机构ID
        //检查是否传递orgId
        String orgId = request.getHeader("orgId");
        if (orgId == null) {
            Result result = ResultUtil.paramError("orgId不能为空");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSONUtil.toString(result));
            return false;
        }

        Session session = SecurityUtils.getSubject().getSession();
        SysUser sysUser = (SysUser) session.getAttribute(SessionAttr.MS_USER);

        //查找用户是否拥有该组织机构权限
        Integer deptId = sysDeptService.getDeptByGuidAndUser(orgId, sysUser.getId(), sysUser.getType());
        if (deptId == null) {
            Result result = ResultUtil.paramError("组织机构不存在");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSONUtil.toString(result));
            return false;
        }
        logger.debug("deptId:{}", deptId);
        request.setAttribute(RequestAttr.DEPT_ID, deptId);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
